import React, { createContext, useEffect, useReducer, useState } from 'react';
import { useHistory } from "react-router-dom";
import { Spin } from "antd";
import { projectAPI } from "../apis/project";
import store from "store";

// Context
export const ProjectContext = createContext({});

interface ProjectData {
  current?: string;
  list?: any[]
  loading?: boolean
}

// Reducer
export const ProjectReducer = (state: object, action: {
  type: string;
  data: ProjectData;
}) => {
  if (action.data.current) {
    store.set("S_MAN_APP", action.data.current);
  }

  switch(action.type) {
    case "SET_LOADING":
    case "LOAD_LIST":
    case "SET_PROJECT":
      return {
        ...state,
        ...action.data
      }
  }
  return state;
}

export const ProjectProvider = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [project, dispatcher] = useReducer(ProjectReducer, {
    list: [],
    current: ''
  });

  // 改变应用后，子视图需要重新加载
  function changeProject(value: string) {
    dispatcher({
      type: 'SET_LOADING',
      data: {
        loading: true,
        current: value
      }
    });
    setTimeout(() => {
      dispatcher({
        type: 'SET_LOADING',
        data: {
          loading: false
        }
      });
    })
  }

  const h = useHistory();
  const whiteConf = ["/error", "/perform"];
  const showProject = whiteConf.some((it) => {
    return (h.location.pathname).indexOf(it) === 0;
  });

  function getProjectList() {
    setLoading(true);
    projectAPI.projectList({}).then((res: any) => {
      if (res && res.success) {
        dispatcher({
          type: 'LOAD_LIST',
          data: {
            list: res.data.list
          }
        });
        if (res.data.list.length) {
          const value = store.get("S_MAN_APP") || res.data.list[0].app_secret
          dispatcher({
            type: 'SET_PROJECT',
            data: {
              current: value
            }
          });
        }
      }
    }).finally(() => {
      setLoading(false);
    })
  }

  useEffect(() => {
    getProjectList()
  }, [])

  if (loading) {
    return (
      <div className="full-spin">
        <Spin />
      </div>
    )
  }

  const renderChildren = () => {
    if (showProject) {
      return (project as any).list.length ? props.children : <div>请先添加应用</div>
    }
    return props.children;
  }

  return (
    <ProjectContext.Provider
      value={{
        project,
        dispatcher,
        showProject,
        loading,
        changeProject
      }}>
      {renderChildren()}
    </ProjectContext.Provider>
  )
}